import { ElMessage } from "element-plus";
import { createRouter, createWebHistory } from "vue-router";
import { useUserStore } from "../stores/userStore.js";
import Home from "../views/home/Home.vue";
import History from "../views/history/History.vue";
import User from "../views/user/User.vue";
import Edit from "../../src/components/Edit.vue";
import Setting from '../components/Seting.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: "/",
      name: "home",
      // component: () => import("../views/layout/Layout.vue"),
      component: Home,
      children: [
        {
          path: '/home',
          name: 'home',
          component: Home,
         //权限校验标识
          // meta: {
          //           isAuth: true
          //         }
        },
     
      ],
    },
    {
      path: "/history",
      name: "history",
      component: History,
    },
    {
      path: "/user",
      name: "user",
      component: User,
    },
    {
      path: "/edit",
      name: "edit",
      component: Edit,
    },
    {
      path: "/setting",
      name: "setting",
      component: Setting,
    },
    
  ],
  // 跳转页面时直接回到顶部
  scrollBehavior() {
    return {
      top: 0,
    };
  },
});

// 配置路由导航
router.beforeEach((to, from, next) => {
  // 判断资源是否要拦截
  if (to.matched.some((route) => route.meta.isAuth)) {
    // 如果资源要拦截, 判断是否有token
    const token = useUserStore().token;
    // 如果token存在, 直接放行
    if (token) {
      next();
    } else {
      // 没有token 跳转登录页
      ElMessage.warning("请先登录");
      next({
        path: "/login",
      });
    }
  } else {
    // 请求的资源不需要拦截 直接放行
    next();
  }
});

export default router;
